#pragma once
#include <iostream>
#include <functional>
#include <pthread.h>
#include <string>

namespace ns_thread
{
    template <class T>
    using func_t = std::function<void(T&)>;

    template <class T>
    class Thread
    {
    private:
        void Excute()
        {
            _func(_data);
        }
    public:
        Thread(func_t<T> func, T& data, const std::string& who = "None name")
            : _data(data),
              _func(func),
              _name(who),
              _running(false)
        {
        }

        static void* threadrun(void* args)
        {
            Thread<T>* self = (Thread<T>*)args;
            self->Excute();
            return nullptr;
        }

        bool start()
        {
            int n = pthread_create(&_tid, nullptr, threadrun, this);
            if (n == 0)
            {
                _running = true;
                return true;
            }
            else
            {
                return false;
            }
        }
        void Join()
        {
            if (_running == true)
            {
                pthread_join(_tid, nullptr);
            }
        }
        void Detach()
        {
            if (_running == true)
            {
                pthread_detach(_tid);
            }
        }
        void Stop()
        {
            _running = false;
        }
        ~Thread()
        {
        }

    private:
        pthread_t _tid;
        std::string _name; //无论如何都得先初始化？
        func_t<T> _func;
        T& _data;

        bool _running;

    };
}